package org.water.common.log;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.water.base.entity.LogBean;
import org.water.common.param.ConstParams;

import com.alibaba.fastjson.JSON;

/**
 * 日志管理器
 * @author qzy
 *
 */
public class BaseLog {
	
	//private static SysLogger logger=new SysLogger((LoggerContext)LogManager.getContext(),BaseLog.class.toString(),StringFormatterMessageFactory.INSTANCE);
	private static Logger logger=LogManager.getLogger(BaseLog.class);
	
	private static String[] mimes={"js","css","png","jpeg","jpg","woff"};
	
	public static String EMPTY_USER="anonymous";
	/**
	 * 日志集
	 */
	private static HashMap<Long, LogBean> logMap=new HashMap<>();
	/**
	 * 日志记录
	 * @param request
	 * @visitStatus 访问状态
	 */
	public static void recordLog(HttpServletRequest request,String visitStatus)
	{
		if(request!=null)
		{
			String requestUrl=request.getRequestURI();
			Subject subject=SecurityUtils.getSubject();
			String user=EMPTY_USER;
			if(!isStaitc(requestUrl))
			{
				if(subject!=null && subject.getSession().getAttribute(ConstParams.CURRENT_USERNAME)!=null)
				{
					user=subject.getSession().getAttribute(ConstParams.CURRENT_USERNAME).toString();
				}
				logger.info(user+" "+visitStatus+" visit "+requestUrl);
			}
			
		}
	}
	/**
	 * 判断是否是静态文件
	 * @param url
	 * @return
	 */
	private static boolean isStaitc(String url)
	{
		boolean f=false;
		String[] urls=url.split("\\.");
		if(urls.length>0)
		{
			String mime=urls[urls.length-1];
			for(String m:mimes)
			{
				if(m.equalsIgnoreCase(mime))
				{
					f=true;
					break;
				}
			}
		}
		return f;
	}
	
	/**
	 * 获取日志bean
	 * @param threadId
	 * @return
	 */
	public static LogBean getLogBean(Long threadId)
	{
		return logMap.get(threadId);
	}
	/**
	 * 
	 * @param logBean
	 */
	public static void addLogBean(LogBean logBean)
	{
		logMap.put(logBean.getExecThreadId(), logBean);
	}
	/**
	 * 记录日志并销毁日志
	 * @param logBean
	 */
	public static void recordLog(LogBean logBean)
	{
		if(logBean!=null)
		{
			logger.info(JSON.toJSONString(logBean));
			logMap.remove(logBean.getExecThreadId());
			logBean=null;
		}
	}
}
